<template>
  <content-field>
    <n-grid :cols="10" x-gap="24" item-responsive responsive="screen">
      <n-gi span="0 m:2">
        <n-card title="辅助函数"></n-card>
      </n-gi>
      <n-gi span="10 m:8"
        ><n-card :segmented="{ content: 'soft' }">
          <template #header>
            <back-last />
            {{ is_create ? "创建" : "编辑" }}文章<n-text depth="3">
              #{{ article.id }}
            </n-text>
          </template>
          <template #header-extra>
            <n-space v-if="is_create">
              <n-button type="primary" dashed @click="createBtn">
                创建
              </n-button>
            </n-space>
            <n-space v-else
              ><n-button type="info" dashed @click="UpdateBtn"> 更新 </n-button>
              <n-button type="error" dashed @click="DeleteConfirm">
                删除
              </n-button></n-space
            >
          </template>
          <n-form label-placement="top">
            <n-grid :cols="24" x-gap="24">
              <n-form-item-gi :span="12" label="文章标题" path="title">
                <n-input v-model:value="article.title" placeholder="文章标题" />
              </n-form-item-gi>
              <n-form-item-gi :span="6" label="创建时间" path="create_time">
                <!-- <n-date-picker
                  disabled
                  v-model:value="article.create_time"
                  type="datetime"
                /> -->
                <n-time :time="article.create_time"></n-time>
              </n-form-item-gi>
              <n-form-item-gi :span="6" label="最后更新于" path="update_time">
                <!-- <n-date-picker
                  disabled
                  v-model:value="article.update_time"
                  type="datetime"
                /> -->
                <n-text v-if="is_create">————</n-text>
                <n-time v-else :time="article.update_time"></n-time>
              </n-form-item-gi>

              <n-form-item-gi :span="24" label="简介" path="brief">
                <n-input v-model:value="article.brief" placeholder="文章简介" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="收录于" path="colloection">
                <collection-index-card ref="collectioninput" />
              </n-form-item-gi>
              <n-form-item-gi :span="6" label="公开状态" path="is_active">
                <n-switch v-model:value="article.is_active">
                  <template #checked> 广播中 </template>
                  <template #unchecked> 未广播 </template>
                </n-switch>
              </n-form-item-gi>
              <n-form-item-gi :span="24" label="标签" path="badges">
                <badge-index-card ref="badgesintput" />
              </n-form-item-gi>
              <n-form-item-gi :span="24" label="正文" path="content">
                <v-md-editor
                  v-model="article.content"
                  height="600px"
                  left-toolbar="image"
                />
              </n-form-item-gi>
            </n-grid>
          </n-form>
          <template #action>
            <n-space justify="end">
              <n-button
                v-if="is_create"
                type="primary"
                dashed
                @click="createBtn"
                >创建</n-button
              >
              <n-button v-else type="info" dashed @click="UpdateBtn">
                更新
              </n-button></n-space
            >
          </template>
        </n-card></n-gi
      >
    </n-grid>
  </content-field>
</template>

<script>
import ContentField from "@/components/ContentField.vue";
import { onBeforeMount, ref } from "vue";

import { useMessage, useDialog, NSwitch } from "naive-ui";

import BackLast from "@/components/BackLast.vue";
import BadgeIndexCard from "@/components/cards/BadgeIndexCard.vue";
import { useStore } from "vuex";
import CollectionIndexCard from "@/components/cards/CollectionIndexCard.vue";
import remoteData from "@/composables/RemoteData";
import routerJump from "@/composables/RouterJump";
import submitData from "@/composables/SubmitData";
export default {
  props: {
    id: {
      type: String,
    },
  },
  components: {
    ContentField,
    BackLast,
    BadgeIndexCard,
    CollectionIndexCard,
    NSwitch,
  },

  setup(props) {
    let article = ref({
      id: "",
      title: "",
      brief: "",
      author: "",
      author_id: "",
      collection: [],
      content: "",
      badges: [],
      create_time: new Date().valueOf(),
      update_time: null,
    });

    const collectioninput = ref(null);
    const badgesintput = ref(null);
    const formRef = ref(null);
    let is_create = ref(false);

    const store = useStore();
    const message = useMessage();
    const dialog = useDialog();

    const { get_article_details } = remoteData();
    const { update_article, delete_article, create_article } = submitData(
      store.state.user.id
    );
    const { go_404, to_article_list, to_article_detail } = routerJump();

    is_create.value = parseInt(props.id) == -1;

    if (!is_create.value) {
      get_article_details(article, props.id)
        .then(() => {
          /** 合集 标签 信息注入*/
          badgesintput.value.setSelectArray(article.value.badges);
          collectioninput.value.setSelect(article.value.collection);
        })
        .catch(() => {
          go_404();
        });
    }
    // 传入id， 编辑模式信息获取

    // 更新上传
    const UpdateBtn = () => {
      article.value.badges = badgesintput.value.getSelectArray();
      article.value.collection_id = collectioninput.value.getSelect();

      update_article(props.id, article)
        .then(() => {
          badgesintput.value.setSelectArray(article.value.badges);
          collectioninput.value.setSelect(article.value.collection);
          message.success(
            `${new Date(
              article.value.update_time
            ).toLocaleTimeString()}更新成功`
          );
        })
        .catch((error) => {
          message.error(`更新失败 {code:${error.response.status}}`);
        });
    };

    // 删除
    const DeleteConfirm = () => {
      dialog.warning({
        title: "警告",
        content: `确定删除文章 《${article.value.title}》 #${article.value.id}`,
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
          delete_article(props.id)
            .then(() => {
              message.success("删除成功");
              to_article_list();
            })
            .catch(() => {
              message.error("删除失败");
            });
        },
        onNegativeClick: () => {
          message.info("取消删除");
        },
      });
    };

    // 创建
    const createBtn = () => {
      article.value.badges = badgesintput.value.getSelectArray();
      article.value.collection_id = collectioninput.value.getSelect();

      create_article(article)
        .then((data) => {
          message.success("创建成功");
          to_article_detail(data.id);
        })
        .catch((error) => {
          message.error(`创建失败  ${JSON.stringify(error.response.data)}`);
          dialog.error({
            title: "创建失败",
            content: `${JSON.stringify(error.response.data)}`,
            positiveText: "确定",
          });
        });
    };
    return {
      go_404,
      get_article_details,

      formRef,
      article,
      badgesintput,
      DeleteConfirm,
      onBeforeMount,
      UpdateBtn,
      createBtn,
      is_create,
      collectioninput,
    };
  },
};
</script>

<style scoped>
</style>